import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import moment from 'moment';
import {
  Table,
  Input,
  Select,
  Progress,
  Icon,
  Confirm,
  Message,
  Pagination,
  Tooltip,
} from '@knownsec/react-component';
import { getTask, cancelTask,getHistoryTask } from '~/API/index';
import './index.less';
import {NotifyType} from '@/common/common'
const option = [
  { label: '安全事件', value: 'securityEvent' },
  { label: '漏洞', value: 'vul' },
  { label: '可用性', value: 'availability' },
  // { label: '业务系统信息', value: 'target_info' },
  { label: '风险外链', value: 'risk_link' },
  { label: '篡改', value: 'change_check' },
];
const bgC={8:'#999EA8',9:'#11AB4E',10:'#F04038'}
class CompTable extends Component {
  constructor(props) {
    super(props);
    this.columns = {
        3:[
        {
          key: 'target_name',
          dataIndex: 'target_url',
          title: '业务系统',
          render: (e, row) => {
            const name = row.target_name ? row.target_name : row.target_title;
            return (
              <Tooltip
                overlay={
                  <>
                    <p>业务系统：{e}</p>
                    <p>业务系统名称：{name || '暂未设置'}</p>
                  </>
                }
                placement="topLeft"
              >
                <div>
                  <p className="targetName">
                      <Link
                          to="#"
                          onClick={() => {
                          window.open(e);
                          }}
                          >
                          {e}
                      </Link>
                  </p>
                  <div className="targetName" style={{ color: name ? '#2A2B31' : '#ccc' }}>
                    {name || '-'}
                  </div>
                </div>
              </Tooltip>
            );
          },
        },
        {
          key: 'target_group_name',
          dataIndex: 'target_group_name',
          className: 'w_8',
          title: '任务组名称',
        },
        {
          key: 'task_type',
          dataIndex: 'task_type',
          className: 'w_8',
          title: '监测项',
          render: (value) => {
            return option.filter((item) => item.value == value)[0]['label']},
        },
        {
          key: 'last_started_at',
          dataIndex: 'last_started_at',
          title: '开始时间',
          render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
        },
        {
          key: 'interview',
          dataIndex: 'interview',
          className: 'w_8',
          title: '耗时',
          render: (value, _data) => this.caleTimes(_data.last_started_at),
        },
        {
          key: 'progress',
          dataIndex: 'progress',
          title: '进度',
          width: 220,
          render: (value, _data) => (
            <div className="processBox">
              <Progress
                className={value == 100 ? '' : 'active_progress'}
                percent={value + '%'}
                color={value == 100 ? '#52c41a' : '#1890ff'}
              />
              <span className="processNum">{value?value.toString().split('.')[0] + '%': '0%'}</span>
              <Icon className="delIcon" type="cancel" onClick={() => this.cancelTasks(_data)} />
            </div>
          ),
        },
      ],
      1:[
          {
            key: 'target_name',
            dataIndex: 'target_url',
            title: '业务系统',
            render: (e, row) => {
              const name =  row.target_name ? row.target_name : row.target_title;
              return (
                <Tooltip
                  overlay={
                    <>
                      <p>业务系统：{e}</p>
                      <p>业务系统名称：{name || '暂未设置'}</p>
                    </>
                  }
                  placement="topLeft"
                >
                  <div>
                    <p className="targetName">{e}</p>
                    <div className="targetName" style={{ color: name ? '#2A2B31' : '#ccc' }}>
                      {name || '-'}
                    </div>
                  </div>
                </Tooltip>
              );
            },
          },
          {
            key: 'target_group_name',
            dataIndex: 'target_group_name',
            title: '任务组名称',
          },
          {
            key: 'task_type',
            dataIndex: 'task_type',
            title: '监测项',
            render: (value) => option.filter((item) => item.value == value)[0]['label'],
          },
          {
            key: 'next_start_at',
            dataIndex: 'next_start_at',
            title: '等待调度时间',
            render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
          },
          {
            key: 'interview',
            dataIndex: 'interview',
            title: '耗时',
            render: (value, _data) => this.caleTimes(_data.last_started_at),
          },
        ],
        2:[
            {
                key: 'target_name',
                dataIndex: 'target_url',
                title: '业务系统',
                render: (e, row) => {
                    const name = row.target_name ? row.target_name : row.target_title;
                    return (
                        <Tooltip
                            overlay={
                                <>
                                    <p>业务系统：{e}</p>
                                    <p>业务系统名称：{name || '暂未设置'}</p>
                                </>
                            }
                            placement="topLeft"
                        >
                            <div>
                                <p className="targetName">
                                    <Link
                                        to="#"
                                        onClick={() => {
                                            window.open(e);
                                        }}
                                    >
                                        {e}
                                    </Link>
                                </p>
                                <div
                                    className="targetName"
                                    style={{ color: name ? '#2A2B31' : '#ccc' }}
                                >
                                    {name || '-'}
                                </div>
                            </div>
                        </Tooltip>
                    );
                },
            },
            {
                key: 'target_group_name',
                dataIndex: 'target_group_name',
                className: 'w_8',
                title: '任务组名称',
            },
            {
                key: 'task_type',
                dataIndex: 'task_type',
                className: 'w_8',
                title: '监测项',
                render: (value) => {
                  return option.filter((item) => item.value == value)[0]['label']},
              },
            {
                key: 'status',
                dataIndex: 'status',
                className: 'w_8',
                title: '任务状态',
                render:(e)=>{return <div className="NotifyType"><span className="NotifyType_1" style={{ background:bgC[e] }}></span>{NotifyType[e]}</div>}
            },
            {
                key: 'updated_at',
                dataIndex: 'updated_at',
                title: '监测完成时间',
                render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'),
            },
            {
                key: 'reason',
                dataIndex: 'reason',
                className: 'w_8',
                title: '失败原因',
                render:(e)=>{return e||'--'}
            },
        ]}
    this.timer = null;
    this.state = {
      dataList: { data: [], total: 0 },
      task_type: [],
      taskTotal: {},
      target_group_name: this.props.taskname || '',
      target_name: '',
      target_url: '',
      page: 1,
      limit: 10,
      loading: false
    };
  }
  caleTimes(start) {
    if (start) {
      start = new Date(start).getTime();
      const end = new Date().getTime();
      if (end <= start) {
        return '0时0分';
      }
      const longs =
        Math.floor(moment.duration(end - start).asHours()) +
        '小时' +
        moment.duration(end - start).minutes() +
        '分';
      return longs;
    } else {
      return '-';
    }
  }
  componentDidMount() {
    if (this.props.flag === '2') {
        this.getData();
    } else {
        this.getData();
        this.timer = setInterval(() => {
            this.getData();
        }, 30 * 1000);
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer);
    this.timer = null;
  }
  cancelTasks(data) {
    var _this = this;
    Confirm({
      title: '确认提示',
      pro: true,
      message: <div className="confirmbox">确认要取消该任务吗？</div>,
      onconfirm: () => {
        // data.task_id
        cancelTask({ task_ids: [data.task_id] }).then((res) => {
          if (res.status == 'success') {
            _this.getData();
            Message.show({
              pro: true,
              type: 'success',
              message: '操作成功',
              showClose: false,
            });
          }
        });
      },
      oncancel: () => {
        // Message.show({
        //   type: 'info',
        //   message: '已取消操作',
        // });
      },
    });
  }
  setVal(label, val) {
    this.setState({
      [label]: val,
    });
  }
  onSearchChange = (page) => {
    var _this = this;
    if (page.page) {
      _this.setState(
        {
          page: page.page,
          limit: page.limit,
        },
        function () {
          _this.getData();
        }
      );
    } else {
      _this.setState(
        {
          page: 1,
          limit: 10,
        },
        function () {
          _this.getData();
        }
      );
    }
  };
  // onSearchChange(page) {
  // };
  renderSearch(flag) {
    return (
      <>
        <Select
          option={option}
          pro
          placeholder="请选择监测项"
          className="selectItem"
          clearable
          value={this.state.task_type}
          onChange={({ selectedItem }) => {
            this.setVal('task_type', [selectedItem[0] ? selectedItem[0].value : '']);
            return this.getData(selectedItem[0] ? selectedItem[0].value : '', 'change');
          }}
        />
        <Input
          pro
          placeholder="搜索业务系统名称"
          value={this.state.target_name}
          className="searchName search-button"
          search
          onSearch={this.onSearchChange}
          clear
          onChange={(value) => {
            this.setVal('target_name', value.value);
            if (!value.e) {
              this.onSearchChange({ val: 'target_name' });
            }
          }}
        ></Input>
        <Input
          pro
          placeholder="搜索任务组名称"
          value={this.state.target_group_name}
          className="searchName search-button"
          search
          onSearch={this.onSearchChange}
          clear
          onChange={(value) => {
            this.setVal('target_group_name', value.value);
            if (!value.e) {
              this.onSearchChange({ val: 'target_group_name' });
            }
          }}
        ></Input>
        <Input
          pro
          placeholder="搜索业务系统地址"
          value={this.state.target_url}
          search
          className="search-button last"
          onSearch={this.onSearchChange}
          clear
          onChange={(value) => {
            this.setVal('target_url', value.value);
            if (!value.e) {
              this.onSearchChange({ val: 'target_url' });
            }
          }}
        ></Input>
      </>
    );
  }
  getData =async (name, type) => {
    let conditions = {
      page: this.state.page,
      limit: this.state.limit,
      status: this.props.flag,
      target_name: this.state.target_name,
      target_group_name: this.state.target_group_name,
      target_url: this.state.target_url,
      task_type: name ? name : type ? '' : this.state.task_type[0] || '',
    };
    if (type) {
      conditions.page = 1;
      conditions.limit = 10;
      this.setVal('page', 1);
      this.setVal('limit', 10);
    }
    this.setState({ loading: true })
    if (this.props.flag === "2") {
        const res= await getHistoryTask(conditions)
        this.setState({ loading: false })
        if(res.status === 'success'){
            this.setVal('dataList', res.data || {});
        }
    }else{
        getTask(conditions)
        .then((res) => {
          this.setState({ loading: false })
            if (res.status == 'success') {
                this.setVal('dataList', res.data || {});
            }
        })
        .finally(() => {});
    }
  };

  render() {
    const { flag } = this.props;
    return (
      <div className="maintable">
        <div className="searchBox">
          <div className="searchRight">{this.renderSearch(this.props.flag)}</div>
        </div>
        <Table 
          columns={this.columns[flag]}
          data={this.state.dataList.data}
          tableLoading={this.state.loading}
          loadingLabel=""
          ></Table>
        {this.state.dataList.total > 10 && <Pagination
          key={Number(123)}
          className="pagination"
          current={this.state.page}
          showQuickJumper={{ goButton: true }}
          showSizeChanger={true}
          showTotal={(total) => `共${total}条`}
          pageSize={this.state.limit}
          pageSizeOptions={['10', '20', '50']}
          total={this.state.dataList.total}
          onChange={(page, size) => {
            this.onSearchChange({ page, limit: size });
          }}
        />}
      </div>
    );
  }
}

export default CompTable;
